package entity;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class BaseDao {
	private static String driver;
	private static String url;
	private static String user;
	private static String password;
	Connection con = null;
	
	//静态代码块，保证类加载的同时执行
	static {
		init();
	}
	//从配置文件中获得参数
	public static void init() {
		//创建Properties类的对象
		Properties pt = new Properties();
		String file = "dataBase.properties";
		//加载配置文件到输入流
		InputStream is = BaseDao.class.getClassLoader().getResourceAsStream(file);
		//从输入流中读取属性
		try {
			pt.load(is);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		driver = pt.getProperty("driver");
		url = pt.getProperty("url");
		user = pt.getProperty("user");
		password = pt.getProperty("password");
		
	}
	
	//加载驱动并连接数据库
	public Connection getConnection() {
		try {
			Class.forName(driver);
			con =DriverManager.getConnection(url,user,password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return con;
	}
	
	//关闭所有资源
	public void closeAll(Connection con, PreparedStatement ps , ResultSet rs) {
		if(rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(ps != null) {
			try {
				ps.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(con != null) {
			try {
				con.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	//增  删  改 的集合方法
	public  int exeUpdate(String sql, Object[] args) {
		con = getConnection();
		PreparedStatement ps = null;
		int row = 0;
		try {
			ps = con.prepareStatement(sql);
			//为参数赋值
			if(args != null) {
				for (int i = 0; i < args.length; i++) {
					ps.setObject(i + 1, args[i]);
				}
			}
			row =ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			closeAll(con, ps, null);
		}
		return row;
	}
}
